package com.youmans.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youmans.eduservice.entity.EduCourse;
import com.youmans.eduservice.entity.EduCourseDescription;
import com.youmans.eduservice.entity.frontVo.CourseFrontVo;
import com.youmans.eduservice.entity.frontVo.CourseWebVo;
import com.youmans.eduservice.entity.vo.CourseInfoVo;
import com.youmans.eduservice.entity.vo.CoursePublishVo;
import com.youmans.eduservice.entity.vo.CourseQuery;
import com.youmans.eduservice.mapper.EduCourseMapper;
import com.youmans.eduservice.service.EduChapterService;
import com.youmans.eduservice.service.EduCourseDescriptionService;
import com.youmans.eduservice.service.EduCourseService;
import com.youmans.eduservice.service.EduVideoService;
import com.youmans.servicebase.exceptionHandler.GuliException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author Youmans
 * @since 2022-05-07
 */
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements EduCourseService {

    @Autowired
    private EduCourseDescriptionService eduCourseDescriptionService ;

    @Autowired
    private EduVideoService eduVideoService ;
    @Autowired
    private EduChapterService eduChapterService ;

    private int count = 0;

    @Override
    public String saveCourseInfo(CourseInfoVo courseInfoVo) {
        //向课程表添加课程基本信息
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo,eduCourse);
        int insert = baseMapper.insert(eduCourse);

        if(insert == 0){
            throw new GuliException(20001,"添加课程信息失败");
        }

        //获取添加之后的课程id
        String cid = eduCourse.getId() ;
        //向课程简介表添加信息
        EduCourseDescription courseDescription = new EduCourseDescription();
        courseDescription.setDescription(courseInfoVo.getDescription()) ;
        //设置描述id为课程id
        courseDescription.setId(cid) ;
        eduCourseDescriptionService.save(courseDescription) ;
        return cid ;
    }

    @Override
    public CourseInfoVo getCourseInfo(String courseId) {
        EduCourse eduCourse = baseMapper.selectById(courseId);
        EduCourseDescription courseDescription = eduCourseDescriptionService.getById(courseId);
        CourseInfoVo vo = new CourseInfoVo();
        BeanUtils.copyProperties(eduCourse,vo);
        if(StringUtils.isEmpty(courseDescription)){
            vo.setDescription(null);
        }else{
            vo.setDescription(courseDescription.getDescription());
        }
        return vo;
    }

    @Override
    public void updateCourseInfo(CourseInfoVo courseInfoVo) {
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo,eduCourse);
        int insert = baseMapper.updateById(eduCourse);
        if(insert == 0){
            throw new GuliException(20001,"添加课程信息失败");
        }
        //获取添加之后的课程id
        String cid = eduCourse.getId() ;
        //向课程简介表添加信息
        EduCourseDescription courseDescription = new EduCourseDescription();
        courseDescription.setDescription(courseInfoVo.getDescription()) ;
        //设置描述id为课程id
        courseDescription.setId(cid) ;
        eduCourseDescriptionService.updateById(courseDescription) ;
    }

//    根据课程id查询课程确认信息
    @Override
    public CoursePublishVo getPublishCourseInfo(String id) {
        return baseMapper.getPublishCourseInfo(id);
    }

    @Override
    public IPage<EduCourse> pageCondition(Page<EduCourse> pageCourse, CourseQuery courseQuery) {
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        String name = courseQuery.getTitle();
        String status = courseQuery.getStatus();
        String begin = courseQuery.getBegin();
        String end = courseQuery.getEnd();
        //判断条件值是否为空，如果不为空拼接条件
        if(!StringUtils.isEmpty(name)) {
            //构建条件
            try {
                //请求可能乱码
                wrapper.like("title", URLDecoder.decode(name,"UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        if(!StringUtils.isEmpty(status)) {
            wrapper.eq("status",status);
        }
        if(!StringUtils.isEmpty(begin)) {
            wrapper.ge("gmt_create",begin);
        }
        if(!StringUtils.isEmpty(end)) {
            wrapper.le("gmt_create",end);
        }
        //排序
        wrapper.orderByDesc("view_count");
        IPage<EduCourse> studentPage = baseMapper.selectPage(pageCourse, wrapper);

        return studentPage;
    }

    //删除课程
    @Transactional
    @Override
    public void removeCourse(String courseId) {
//        依次删除小节，章节，描述，课程
        eduVideoService.removeVideoByCourseId(courseId) ;
        eduChapterService.removeChapterByCourseId(courseId) ;
        eduCourseDescriptionService.removeById(courseId) ;
        int deleteById = baseMapper.deleteById(courseId);
        if(deleteById == 0){
            throw new GuliException(20001,"删除失败");
        }
    }
//    @Cacheable(value = "course",key = "'selectList'")
    @Override
    public List<EduCourse> getList() {
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>() ;
        wrapper.orderByDesc("id") ;
        wrapper.last("limit 4") ;
        return  baseMapper.selectList(wrapper) ;
    }

//    根据教师id 查询课程列表
    @Override
    public List<EduCourse> getListByTeacherId(String teacherId) {
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>() ;
        wrapper.eq("teacher_id",teacherId) ;
        return    baseMapper.selectList(wrapper);
    }

    @Override
    public Map<String, Object> getCourseFrontList(Page<EduCourse> page, CourseFrontVo courseFrontVo) {
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>() ;
//        一级分类
        if(!StringUtils.isEmpty(courseFrontVo.getSubjectParentId())){
            wrapper.eq("subject_parent_id",courseFrontVo.getSubjectParentId());
        }
//        二级分类
        if(!StringUtils.isEmpty(courseFrontVo.getSubjectId())){
            wrapper.eq("subject_id",courseFrontVo.getSubjectId());
        }
        if(!StringUtils.isEmpty(courseFrontVo.getBuyCountSort())){
            if(count == 0){
                wrapper.orderByDesc("buy_count");
                count =1 ;
            }else{
                wrapper.orderByAsc("buy_count");
                count = 0 ;
            }

        }
        if(!StringUtils.isEmpty(courseFrontVo.getGmtCreateSort())){
//            wrapper.orderByDesc("gmt_create");
            if(count == 0){
                wrapper.orderByDesc("gmt_create");
                count =1 ;
            }else{
                wrapper.orderByAsc("gmt_create");
                count = 0 ;
            }
        }
        if(!StringUtils.isEmpty(courseFrontVo.getPriceSort())){
//            wrapper.orderByDesc("price");
            if(count == 0){
                wrapper.orderByDesc("price");
                count =1 ;
            }else{
                wrapper.orderByAsc("price");
                count = 0 ;
            }
        }
        baseMapper.selectPage(page,wrapper) ;

        List<EduCourse> records = page.getRecords();
        long current = page.getCurrent();
        long pages = page.getPages();
        long size = page.getSize();
        long total = page.getTotal();
        boolean hasNext = page.hasNext();//下一页
        boolean hasPrevious = page.hasPrevious();//上一页

        //把分页数据获取出来，放到map集合
        Map<String, Object> map = new HashMap<>();
        map.put("items", records);
        map.put("current", current);
        map.put("pages", pages);
        map.put("size", size);
        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);

        //map返回
        return map;
    }

    @Override
    public CourseWebVo getBaseCourseInfo(String courseId) {
        return baseMapper.getBaseCourseInfo(courseId);
    }

}
